package com.yami.shop.api.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yami.shop.bean.app.dto.UserXsCardDto;
import com.yami.shop.bean.app.param.UserXsCardParam;
import com.yami.shop.bean.model.SysMsg;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserXsCard;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.UserService;
import com.yami.shop.service.UserXsCardService;
import io.rong.models.group.GroupMember;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户绑卡服务
 *
 * @author LGH
 */
@RestController
@RequestMapping("/p/user/xs/card")
@Tag(name = "用户绑卡接口")
@AllArgsConstructor
public class UserXsCardController {

    private final UserXsCardService userXsCardService;


    @GetMapping("/getUserCardList")
    @Operation(summary = "获取用户绑卡列表", description = "根据用户id或者新生账户Id获取用户绑卡列表")
    public ServerResponseEntity<List<UserXsCardDto>> getUserCardList() {
        String userId = SecurityUtils.getUser().getUserId();
        List<UserXsCard> userCardsByUserIdOrXsUserId = userXsCardService.getUserCardsByUserIdOrXsUserId(userId, null);
        List<UserXsCardDto> userXsCardDtos = BeanUtil.copyToList(userCardsByUserIdOrXsUserId, UserXsCardDto.class);
        return ServerResponseEntity.success(userXsCardDtos);
    }

    @GetMapping("/getUserCardById/{id}")
    @Operation(summary = "获取用户绑卡信息", description = "根据用户id或者新生账户Id获取用户绑卡列表")
    public ServerResponseEntity<UserXsCardDto> getUserCardList(@PathVariable("id") Long id) {
        UserXsCard userCardById = userXsCardService.getUserCardById(id);
        UserXsCardDto userXsCardDto = BeanUtil.copyProperties(userCardById, UserXsCardDto.class);
        return ServerResponseEntity.success(userXsCardDto);
    }

    @PostMapping("/cardBinding")
    @Operation(summary = "绑卡接口", description = "绑卡接口")
    public ServerResponseEntity<UserXsCardParam> cardBinding(@Valid @RequestBody UserXsCardParam userXsCardParam) {
        YamiUser user = SecurityUtils.getUser();
        if (!user.getEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.order.pay.user.disable"));
        }
        userXsCardParam.setXsUserId(ObjectUtil.isNotEmpty(userXsCardParam.getXsUserId()) ? userXsCardParam.getXsUserId() : user.getXsUserId());
        try {
            userXsCardParam = userXsCardService.addCard(userXsCardParam,SecurityUtils.getUser().getUserId());
            if (ObjectUtil.isNull(userXsCardParam.getNcountOrderId())) {
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.newborn.binding.order.error"));
            }
            return ServerResponseEntity.success(userXsCardParam);
        }catch (RuntimeException r){
            if(r.getMessage().contains("银行返回账户名称不符")){
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.newborn.binding.check"));
            }
            return ServerResponseEntity.showFailMsg(r.getMessage());
        }
    }

    @PostMapping("/cardBindingConfirm")
    @Operation(summary = "绑卡确认接口", description = "绑卡确认接口")
    public ServerResponseEntity<Void> cardBindingConfirm(@Valid @RequestBody UserXsCardParam userXsCardParam) {
        YamiUser user = SecurityUtils.getUser();
        if (!user.getEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            throw new YamiShopBindException("yami.order.pay.user.disable");
        }
        try {
            boolean b = userXsCardService.addCardConfirm(userXsCardParam);
            if (b) {
                return ServerResponseEntity.success();
            }
        }catch (RuntimeException r){
            return ServerResponseEntity.showFailMsg(r.getMessage());
        }
        return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.newborn.binding.error"));
    }

    @DeleteMapping("/deleteCard/{id}")
    @Operation(summary = "解绑银行卡", description = "根据id，删除绑卡记录")
    @Parameter(name = "id", description = "绑卡记录ID", required = true)
    public ServerResponseEntity<String> deleteCard(@PathVariable("id") String id) {
        YamiUser user = SecurityUtils.getUser();
        if (!user.getEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            throw new YamiShopBindException("yami.order.pay.user.disable");
        }
        UserXsCard userCard = userXsCardService.getUserCardById(Long.valueOf(id));
        if (ObjectUtil.isNull(userCard)) {
            // 该绑卡记录已被删除
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.xscard.delete"));
        }
        try {
            boolean b = userXsCardService.updateCardStatus(Long.valueOf(id), "2");
            if (b) {
                return ServerResponseEntity.success(I18nMessage.getMessage("yami.deleted.xscard.successfully"));
            }
        }catch (RuntimeException r){
            return ServerResponseEntity.showFailMsg(r.getMessage());
        }
        return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.deleted.xscard.fail"));
    }
}
